using JetBrains.Annotations;
using LitJson;
using QFramework;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

public class UpdateStorageInfoCommand : AbstractCommand
{
    protected override void OnExecute()
    {
        StringBuilder urlStringBuilder = new StringBuilder();
        urlStringBuilder.Append(RequestUrl.updateWmsInfoWSUrl);
        MyLogger.Log("updateWmsInfoUrl: " + urlStringBuilder);
        
        if (this.GetSystem<INetworkSystem>().ServerType == ServerType.Local)
        {
#if UNITY_EDITOR
            this.GetSystem<INetworkSystem>().GetLocal(
                url: new StringBuilder(this.GetSystem<INetworkSystem>().HttpBaseUrl)
                                                    .Append(RequestUrl.updateWmsInfoWSUrl).ToString(),
                succStr: (succStr) => {
                    Debug.Log($"Receive {succStr}");
                    OnGetResponseSuccess(succStr);
                    },
                errorStr: OnGetResponseFailure
            );
#endif
        }
        else
        {
            this.GetSystem<INetworkSystem>().ConnectWs(urlStringBuilder.ToString(), 
                serverType: ServerType.WmsServer,
                GetRespondAction: OnGetResponseSuccess);
            /*this.GetSystem<INetworkSystem>().GETHTTP(url: new StringBuilder(this.GetSystem<INetworkSystem>().HttpBaseUrl).Append(RequestUrl.updateWmsInfoUrl).ToString(),
                succStr: OnGetResponseSuccess,
                errorStr: OnGetResponseFailure
                );*/
        }
    }

    private void OnGetResponseSuccess(string succStr)
    {
        JsonData jsonData = JsonMapper.ToObject(succStr);
        if (jsonData.ContainsKey("storageList") && jsonData["storageList"].IsArray)
        {
            JsonData jd = jsonData["storageList"];
            this.GetModel<IStorageModel>().StorageInfos.Clear();

            for (int i = 0; i < jd.Count; i++)
            {
                StorageInfo info = new StorageInfo
                {
                    stock = (int)jd[i]["isStocked"],
                    wareHouseCode = (string)jd[i]["code"]
                };
                this.GetModel<IStorageModel>().StorageInfos.Add(info);

            }
            this.SendEvent(new UpdateStorageInfoEvent());
        }
    }
    private void OnGetResponseFailure(string failStr)
    {
        Debug.LogError($"{failStr}");
    }
}
